import 'package:encrypt/encrypt.dart';
import '../values/index.dart';

/// 加密类
class EncryptUtil {

  // RSA公钥（PEM格式, 与服务端统一）
  static const String rsaPublicKey = '''
-----BEGIN PUBLIC KEY-----
填充公钥值
-----END PUBLIC KEY-----
''';

  // RSA公钥加密
  static String encodeString(String content)  {
    dynamic publicKey = RSAKeyParser().parse(rsaPublicKey);
    final encrypter = Encrypter(RSA(publicKey: publicKey));
    return encrypter.encrypt(content).base64; //返回加密后的base64格式文件
  }

  // // RSA私钥解密
  // static String decodeString(String content)  {
  //   dynamic privateKey = RSAKeyParser().parse(rsaPrivateKey);
  //   final encrypter = Encrypter(RSA(privateKey: privateKey));
  //   return encrypter.decrypt(Encrypted.fromBase64(content));
  // }

  static final EncryptUtil _instance = EncryptUtil._internal();
  factory EncryptUtil() => _instance;
  EncryptUtil._internal() {
    encrypter = Encrypter(AES(
      key,
      mode: AESMode.cbc,
      padding: 'PKCS7',
    ));
  }

  // 此处要与后端保持一致
  final key = Key.fromUtf8(Constants.aesKey);
  final iv = IV.fromUtf8(Constants.aesIV);
  late Encrypter encrypter;

  /// aes加密
  String aesEncode(String content) {
    final encrypted = encrypter.encrypt(content, iv: iv);
    return encrypted.base64;
  }
}
